package cn.xttc.edu.controller;


import cn.xttc.edu.entity.ExpenseRule;
import cn.xttc.edu.entity.ReturnMsg;
import cn.xttc.edu.entity.vo.RuleVo;
import cn.xttc.edu.service.ExpenseRuleService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杨磊
 * @since 2022-02-27
 */
@RestController
public class ExpenseRuleController {

    @Autowired
    private ExpenseRuleService ruleService;

    /**
     * 根据id查询规则
     * @param id id
     * @return 封装对象
     */
    @GetMapping("/rule/{id}")
    public ReturnMsg getRuleById(@PathVariable("id") int id) {
        ExpenseRule rule = ruleService.getById(id);
        return ReturnMsg.success(rule);
    }

    /**
     * 分页查询规则
     * @param pn 当前页码
     * @return 封装对象
     */
    @GetMapping("/rule")
    public ReturnMsg pageGetAll(int pn) {
        Page<RuleVo> page = new Page<>(pn, 5);
        ruleService.pageGetAll(page);
        if (!page.getRecords().isEmpty()) {
            return ReturnMsg.success(page);
        } else {
            return ReturnMsg.fail(null);
        }
    }

    /**
     * 添加规则
     * @param rule 规则对象
     * @return 封装对象
     */
    @PostMapping("/rule")
    public ReturnMsg addRule(ExpenseRule rule) {
        boolean b = ruleService.save(rule);
        if (b) {
            return ReturnMsg.success("添加成功");
        } else {
            return ReturnMsg.fail("添加失败，请联系管理员");
        }
    }

    /**
     * 更新规则
     * @param rule 规则对象
     * @return 封装对象
     */
    @PutMapping("/rule/{id}")
    public ReturnMsg editRule(ExpenseRule rule) {
        boolean b = ruleService.updateById(rule);
        if (b) {
            return ReturnMsg.success("修改成功");
        } else {
            return ReturnMsg.fail("修改失败");
        }
    }

    /**
     * 单个删除和批量删除
     * @param ids id字符串
     * @return 封装对象
     */
    @DeleteMapping("/rule/{ids}")
    public ReturnMsg deleteRules(@PathVariable("ids") String ids) {
        if (ids.contains("-")) {
            //批量删除
            List<Integer> delIds = new ArrayList<>();
            String[] strIds = ids.split("-");
            //组装id的集合
            for (String string : strIds) {
                delIds.add(Integer.parseInt(string));
            }
            try {
                ruleService.removeBatchByIds(delIds);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败，该规则已与订单绑定");
            }
        } else {
            //单个删除
            Integer id = Integer.parseInt(ids);
            try {
                ruleService.removeById(id);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败，该规则已与订单绑定");
            }
        }
        return ReturnMsg.success("删除成功");
    }

}

